package cn.kgc.shiro.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;
import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/8/8
 */
public class CustomerRealm  extends AuthorizingRealm {
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        // 获取用户的身份信息   用户名

        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        //  基于角色授权
        //  TODO  RBAC   根据用户名查询用户的角色信息
        List<String> roles = Arrays.asList("admin");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);

        // 基于权限字符串授权
        // TODO  RBAC   根据用户名查询用户的权限字符串
        List<String> auths = Arrays.asList("user:add", "user:update", "user:delete");
        simpleAuthorizationInfo.addStringPermissions(auths);


        return simpleAuthorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户的身份信息  用户名
        String principal = (String) authenticationToken.getPrincipal();
        // tom   根据用户身份信息 查询数据库
        // 判定 查询的数据是否为null

        if("tom".equals(principal)){
            // 将查询的数据封装  用于密码的验证     token  info
          return   new SimpleAuthenticationInfo("tom","85c78ccc640dc16561c4785aa5ebd557", ByteSource.Util.bytes("hello"),this.getName());

        }

        return null;
    }
}
